package com.ws.shop.action.front;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ws.shop.action.admin.AccessoryAction;
import com.ws.shop.bean.HtmlConfig;
import com.ws.shop.bean.Page;
import com.ws.shop.common.CacheManager;
import com.ws.shop.common.CommonData;
import com.ws.shop.entity.Accessory;
import com.ws.shop.entity.Auction;
import com.ws.shop.entity.AuctionLog;
import com.ws.shop.entity.Goods;
import com.ws.shop.entity.Member;
import com.ws.shop.entity.Sunpic;
import com.ws.shop.service.AuctionCache;
import com.ws.shop.service.AuctionLogService;
import com.ws.shop.service.AuctionService;
import com.ws.shop.service.CategoryService;
import com.ws.shop.service.ExpressService;
import com.ws.shop.service.GoodsService;
import com.ws.shop.service.HtmlService;
import com.ws.shop.service.MemberService;
import com.ws.shop.service.ParticipateService;
import com.ws.shop.service.SunpicService;
import com.ws.shop.service.impl.AuctionCacheImpl;
import com.ws.shop.util.CommonUtil;
import com.ws.shop.util.RequestUtil;
import com.ws.shop.util.SpringUtil;
import com.ws.shop.util.StringUtil;
import com.ws.shop.util.SystemConfigUtil;
import com.ws.shop.util.TemplateConfigUtil;

@Controller
@RequestMapping(value = "/auction/*")
// 请求目录
public class AuctionAction extends BaseFrontAction {
	
	private static Logger log = Logger.getLogger(AuctionAction.class);
	
	@Autowired
	AuctionService auctionService;
	@Autowired
	CategoryService categoryService;
	@Autowired
	AuctionLogService auctionlogService;
	@Autowired
	private SunpicService sunpicService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private ExpressService expressService;
	@Autowired
	private ParticipateService participateService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private AuctionCache auctionCache;
	@Autowired
	private HtmlService htmlService;
	
	@RequestMapping(value = "now.htm", method = RequestMethod.GET)// 请求地址
	public String now(HttpServletRequest request, Model model) {
		int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
		int cid = RequestUtil.getIntParameter(request, "cid", 0);
		int state = RequestUtil.getIntParameter(request, "state", 1);
		int isfree = RequestUtil.getIntParameter(request, "isfree", 0);
		Page page = auctionService.findAuctionListPage(pageno, 16, cid, state,isfree);
		model.addAttribute(Page.PAGE, page);
		model.addAttribute("cid", cid);
		model.addAttribute("state", state);
		model.addAttribute("isfree", isfree);
		return "auction_now";
	}

	@RequestMapping(value = "showauction.htm", method = RequestMethod.POST)// 请求地址
	public String  showauction(HttpServletRequest request,HttpServletResponse response){
		String s = "";
		try{
			 Date rt = new Date();
			 long time =  RequestUtil.getLongParameter(request, "t", 0);
			 int f = RequestUtil.getIntParameter(request, "f" , 1);
			 log.info(" +++++++ f value +++++ " + f + " +++time++++ " + time);
			 String tid = RequestUtil.getStringParameter(request, "gids", "");
			 String[] tids = tid.split(",");
			 log.info("gids : " + String.valueOf(tid)+" tids " + tids[0] );
			 CacheManager cacheManager = new CacheManager(time);
			 s = combination(tids,rt,f,cacheManager);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return ajax(response,s, "text/html");
		
	}
	
	public String combination(String[] tids,Date rt,int f,CacheManager cacheManager){
		 JSONArray jsonarray = new JSONArray();
		 if(tids!=null && tids.length>0){
			 for(int i=0;i<tids.length;i++){
				 if(!StringUtil.isEmpty(tids[i])){
					 long aid = Long.valueOf(tids[i]);
					 Auction auc = CacheManager.getAllAcution().get(aid);
					 if(auc != null){				 
						 Auction auction = cacheManager.robotbid(auc.getId());
						 if(auction!=null){
							 setjsonArray(jsonarray,rt,i,auction);
							 updateState(auction);
						 }else{
							 setjsonArray(jsonarray,rt,i,auc);
							 updateState(auc);
						 }
					 }
				 }
			 }
		 }
		 return jsonarray.toString();
	}
	
	public void updateState(Auction auction){
		if(auction.isIsupdatestate()){
			log.info("++++++++++++update state to 2++++++++++++");
			auctionService.updateAuctionState(auction);
		}
	}
	
	public void setjsonArray(JSONArray jsonarray,Date rt,int i,Auction auction){
		 Map<String,Object> map = new HashMap<String,Object>();
		 map.put("id",String.valueOf(auction.getId()));
		 map.put("c",auction.getAuctionuname());
	     float f = CommonUtil.getScale2(auction.getRealprice()); 
		 map.put("n",String.valueOf(f));
		 if(i==0){
			 map.put("rt", rt.getTime());
			 map.put("st", new Date().getTime());
		 }
		 map.put("l",  auction.getEndtime().getTime());
		 map.put("m", "");
		 map.put("s", auction.getState());
		 map.put("v", new Date().getTime());
		 jsonarray.add(map);
	}
	
	@RequestMapping(value = "bid.htm", method = RequestMethod.POST)// 请求地址
	public String bid(HttpServletRequest request,HttpServletResponse response){
		log.info("+++++++++++++++++++++++bid+++++++++++++++++++++++++++");
		int aid = RequestUtil.getIntParameter(request, "aid", -1);
		Map<String,Object> loginMember = getLoginMember(request.getSession(false));
		Map<String,String> jsonMap = new HashMap<String,String>();
		if(loginMember == null){
			jsonMap.put("status", "nologin");
			return ajaxJson(response, jsonMap);
		}
		Integer uid = (Integer)loginMember.get(Member.LOGIN_MEMBER_ID_KEY);
		log.info("++++aid+++++" + aid + "++++++uid++++++" + uid);
		try{
			System.out.println(" ++++++++++++++++++++++ " + uid + " +++++++++++ ");
			if(uid == null){
				jsonMap.put("status", "nologin");
				return ajaxJson(response, jsonMap);
			}
			Auction info = auctionService.bids(uid, aid);
			if(info == null){
				return this.ajaxJsonErrorMessage(response, "系统忙!");
			}else{
				if(info.getBidstate() == 0){
					jsonMap.put("id", String.valueOf(info.getId()));
					jsonMap.put("currentuser", info.getAuctionuname());
					jsonMap.put("nowprice", String.valueOf(info.getRealprice()));
					jsonMap.put("status", "success");
					jsonMap.put("number", String.valueOf(info.getAuctioncount()));
				}else{
					log.info("返回状态:" + info.getBidstate());
					jsonMap.put("status", String.valueOf(info.getBidstate()));
					jsonMap.put("message", CommonData.AUCTION_STATU_MESSAGE.get(info.getBidstate()));
				}
			}
			jsonMap.put("state", String.valueOf(info.getBidstate()));
		}catch(Exception ex){
			ex.printStackTrace();
			return this.ajaxJsonErrorMessage(response, "系统忙!");
		}
		return this.ajaxJson(response, jsonMap);
	}
	
	// 即将进行的竞拍
	@RequestMapping(value = "future.htm", method = RequestMethod.GET)
	public String future(HttpServletRequest request, Model model) {
		int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
		Page page = auctionService.findAuctionListPage(pageno, 16, 0, 0,-1);
		model.addAttribute(Page.PAGE, page);
		return "auction_future";
	}

	public String switchFuture(int savingprice) {
		String condition = "1=1";
		switch (savingprice) {
		case 1:
			condition = "(a.goodsprice between 0 and 100)";
			break;
		case 2:
			condition = "(a.goodsprice between 100 and 500)";
			break;
		case 3:
			condition = "(a.goodsprice between 500 and 1000)";
			break;
		case 4:
			condition = "(a.goodsprice between 1000 and 2000)";
			break;
		case 5:
			condition = "a.goodsprice > 2000";
			break;
		default:
			break;
		}
		return condition;
	}

	// 历史竞拍
	@RequestMapping(value = "history.htm", method = RequestMethod.GET)
	public String history(HttpServletRequest request, Model model) {
		int cid = RequestUtil.getIntParameter(request, "cid", 3);//测试
		int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
		int isfree = RequestUtil.getIntParameter(request, "isfree", 0);
		Page page = auctionService.findAuctionListPage(pageno, 10, cid, 2, isfree);
		model.addAttribute(Page.PAGE, page);
		model.addAttribute("cid", cid);
		model.addAttribute("isfree", isfree);
		return "auction_history";
	}

	// 历史返现
	@RequestMapping(value = "historylistmoney.htm", method = RequestMethod.GET)
	public String historylistmoney(HttpServletRequest request, Model model) {
		
		return "historylistmoney";
	}
	
	public String switchHistory(int price) {
		String condition = "1=1";
		switch (price) {
		case 1:
			condition = "(a.realprice between 0 and 1)";
			break;
		case 2:
			condition = "(a.realprice between 1 and 5)";
			break;
		case 3:
			condition = "(a.realprice between 5 and 10)";
			break;
		case 4:
			condition = "(a.realprice between 10 and 100)";
			break;
		case 5:
			condition = "a.realprice > 100)";
			break;
		default:
			break;
		}

		return condition;
	}
	
	  //获取竞拍提示
	@RequestMapping(value = "gamestips.htm", method = RequestMethod.GET)
    public String gamesTips(HttpServletRequest request,HttpServletResponse response){
    	int id = RequestUtil.getIntParameter(request, "id", 0);
    	Auction auctiondata =auctionService.findAuctionById(id);
    	Map jsonMap = new HashMap();
    	int istip = 0;
    	int tipstate = 0;
    	if (auctiondata==null){
    		istip = 0; 
    	}else {
    		if (auctiondata.getState() < 2){
    			istip = 0;
    		}else {
    			istip = 1;
    			Map<String,Object> loginMember = getLoginMember(request.getSession(false));
				int uid = (Integer)loginMember.get(Member.LOGIN_MEMBER_ID_KEY);
				if (auctiondata.getUid() == uid){
					tipstate = 0;
					format(auctiondata,jsonMap);
				}else {
					AuctionLog auctionlog = auctionService.findAuctionLog(id, uid);
					if (auctionlog == null){
						tipstate = 3;
						format(auctiondata,jsonMap);
					}else {
						tipstate = 1;
						format(auctiondata,jsonMap);
						double beatsum = auctionService.beatsum(id, uid);
						
						//$config = C('SYSCONFIG');
						double count = auctiondata .getGoodsprice() - beatsum/ SystemConfigUtil.rmb_beat; //换算差价金额
						jsonMap.put("saleprice", count);
					}
				}
    		}
    	}
    	
    	/*$tipdata 竞拍数据
    	 *$tipstate 提示状态 哪种提示 0自己活得结束提示 1提示保价 2第2名 3提示正常结束 4返点 5恭喜他人
    	 *$istip 是否提示 0不提示 1 提示
    	 * [3] 保留无用
    	 * */
    	//$json = array($tipdata,$tipstate,$istip,0);
    	jsonMap.put("tipstate", tipstate);
    	jsonMap.put("istip", istip);
    	return this.ajaxJson(response, jsonMap);
    }
	
	/**
	 * 
	 * @param auctiondata
	 * @param josnMap
	 */
	public void format(Auction auctiondata,Map josnMap){
			if(auctiondata.getState() != 3){
				//$config = C('SYSCONFIG');
				josnMap.put("ordertime", System.currentTimeMillis() + SystemConfigUtil.order_expired * 86400);
			}
             josnMap.put("price", auctiondata.getRealprice());
             josnMap.put("endtime", auctiondata.getOrdertime());
             josnMap.put("productname", auctiondata.getGoodsname());
             josnMap.put("lastopplayer", auctiondata.getAuctionuname());
	}
	
	@RequestMapping(value = "getyugao.htm", method = RequestMethod.GET)
	public String getyugao(HttpServletRequest request,HttpServletResponse response){
		List<Map<String,Object>> yuGaoList = auctionService.findAuctionList(0,10,0);
		Map jsonMap = new HashMap();
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put("yugaoList", yuGaoList);
		return this.ajaxJson(response, jsonMap);
	}
	
	 //竞拍详细页面
	@RequestMapping(value = "detail.htm", method = RequestMethod.GET)
    public String detail(HttpServletRequest request,Model model){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		Auction auction = auctionService.findAuctionById(id);
		//状态大于等于2表示已经完成竞拍，都可以生成静态页面了
		if(auction.getState() >= 2){
			if(StringUtil.isEmpty(auction.getHtml())){
				HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.AUCTIOIN_DETAIL);
				String htmlFilePath = htmlConfig.getHtmlFilePath(auction.getId()+"");
				auction.setHtml(htmlFilePath);
				auctionService.updateHtml(auction.getId(), htmlFilePath);
			}
			File file = new File(SpringUtil.getRealPath(auction.getHtml()));
			if(!file.exists())
				htmlService.auctionDetailBuildHtml(auction);
			return "redirect:"+auction.getHtml();
		}
		Goods goods = goodsService.findGoodsById(auction.getGid());
		List<Accessory> accessoryList = goodsService.findAccessoryListByGoodsId(auction.getGid());
    	Page historyAuctionPage = auctionService.findAuctionListPage(1,4,auction.getCid(),3,auction.getIsfree());
    	model.addAttribute("historyAuctionList", historyAuctionPage.getData());
    	List<Map<String,Object>> yuGaoList = auctionService.findAuctionList(0,10,0);
    	model.addAttribute("yuGaoList", yuGaoList);
    	model.addAttribute("auction", auction);
    	model.addAttribute("goods", goods);
    	model.addAttribute("accessoryList", accessoryList);
    	model.addAttribute("saveImagUrl", AccessoryAction.SAVE_IMAG_URL);
    	int index = auction.getState();
		return "auction_detail_"+index;
    }
	
	 //获取需要补差价数据
	@RequestMapping(value = "ajaxmycount.htm", method = RequestMethod.GET)
    public String ajaxmycount(HttpServletRequest request,HttpServletResponse response){
    	int id = RequestUtil.getIntParameter(request, "id", 0);//竞拍的Id
    	Map<String,Object> loginMember = getLoginMember(request.getSession(false));
    	//$auction_log = D('Auction_log');
    	/*$user = $_SESSION['user'];
    	$map['aid']=array('eq',$id);
    	$map['uid']=array('eq',$user['id']);*/
    	//$auction_logdata = $auction_log->where($map)->field('sum(beat) as self_point_a,sum(pointb) as self_point_b,count(*) as self_bidcount')->find();
    	int userid = (Integer)loginMember.get(Member.LOGIN_MEMBER_ID_KEY);
    	Map<String ,Integer> map = auctionlogService.mycount(id, userid);
    	Integer sumbeat = map.get("sumbeat");
    	Integer sumpoint = map.get("sumpoint");
    	Integer sumpointb = map.get("sumpointb");
    	
    	//$config = C('SYSCONFIG');
		if(sumbeat!=null)sumbeat =0;
		if(sumpoint!=null)sumpoint =0;
		double rmb_beat = 1;//来源于配置，需要配置
    	//$auction_logdata['self_price_point_a'] = $auction_logdata['self_point_a'] / $config['rmb_beat'];
		double self_price_point = sumpointb/rmb_beat;
		Map<String,String> resmap = new HashMap<String,String>();
		resmap.put("sumbeat", String.valueOf(sumbeat));
		resmap.put("sumpoint", String.valueOf(sumpoint));
		resmap.put("self_price_point", String.valueOf(self_price_point));
    	//$json = json_encode($auction_logdata);
    	//echo $json;
    	return this.ajaxJson(response, resmap);
    }
    
    @RequestMapping(value = "buynow.htm", method = RequestMethod.GET)
    public String buynow(HttpServletRequest request,HttpServletResponse response){
    	long id = RequestUtil.getLongParameter(request, "id", 0);
    	Map<String,Object> loginMember = getLoginMember(request.getSession(false));
    	Integer uid = (Integer)loginMember.get(Member.LOGIN_MEMBER_ID_KEY);
    	if (uid == null) {
    		//请登录
    		return this.ajaxJsonErrorMessage(response, "2");
    	}else {
    		boolean isok=auctionService.issaveprice(uid, id);
    		if (!isok){
	    		int c = auctionService.saveInsured(uid, id);
	    		if (c>0){
	    			return this.ajaxJsonSuccessMessage(response, "0"); //保价成功
	    		}else {
	    			  //保价失败
	    			return this.ajaxJsonSuccessMessage(response, "1"); 
	    		}
    		}else {
    			return this.ajaxJsonErrorMessage(response, "3");
    		}
    	}
    }
    
    @RequestMapping(value = "getbuylog.htm", method = RequestMethod.POST)
    public String getbuylog(HttpServletRequest request,HttpServletResponse response){
    	long aid = RequestUtil.getLongParameter(request, "aid", 0);
    	JSONArray jsonarray = new JSONArray();
    	if(aid <= 0)
    		return ajaxJson(response, jsonarray.toString());
    	LinkedList<AuctionLog> loglist = (LinkedList)AuctionCacheImpl.auctionLogCaches.get(aid);
    	if(loglist != null)
    		loglist = (LinkedList<AuctionLog>)loglist.clone();
    	else
    		return ajaxJson(response, jsonarray.toString());
    	Map <String,Object> map = null;
    	AuctionLog al = null;
    	for(int i = loglist.size()-1;i>=0;i--){
    		al = loglist.get(i);
    		map = new LinkedHashMap<String,Object>();
    		map.put("name", al.getName());
    		map.put("bidprice", al.getBidprice());
    		map.put("ip", al.getIp());
    		jsonarray.add(map);
    	}
    	String outString = jsonarray.toString();
    	return ajaxJson(response, outString);
    }

    @RequestMapping(value = "search.htm", method = RequestMethod.GET)
    public String search(HttpServletRequest request,Model model){
    	int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
    	String key = RequestUtil.getStringParameterByGet(request, "key", "");
    	Page page = auctionService.findAuctionListPage(pageno, 20, key);
    	model.addAttribute(Page.PAGE, page);
    	model.addAttribute("key", key);
    	model.addAttribute("saveImagUrl", AccessoryAction.SAVE_IMAG_URL);
    	return "auction_search";
    }
}
